import { httpReqeustApi } from '/@/api/linxyun/base/index.ts';
import { formatStr2Obj } from './tools.js';
import EnumOptions from '/@/components/Linxyun/Datas/enum_options.js';
import { createDDE_SA } from '/@/utils/stringUtil';

const DDE_SA = createDDE_SA(BASE_API.ENT_CODE || 0, 0, 0);
const headers = { 'DDE-SA': DDE_SA, 'Content-Type': 'application/json;charset=UTF-8' };
const httpRequest = httpReqeustApi();
const ColOptType_Update = 0;
const ColOptType_Delete = 1;
// const ColOptType_Details = 2
// const ColOptType_CheckBox = 3
// const ColOptType_Other = 4
class TabPageItem {
	_pageDefines = {
		TabName: '',
		MainParams: null,
		pageDefine: null,
		searchEvent: null,
		addEvent: null,
		exportEvent: null,
		deleteEvent: null,
		updateEvent: null,
		importEvent: null,
		pageprintEvent: null,
		temprintEvent: null,
		otherEvents: [],
		fields: [],
		viewFields: [],
		addFields: [],
		updateFields: [],
		filterFields: [],
		optCols: [], // {ColumnName: 'xx', buttonDefines: []}
		ImportTemp: '',
	};

	getTabName() {
		return this._pageDefines.TabName;
	}

	getPageDefine() {
		return this._pageDefines.pageDefine;
	}

	getMainParams() {
		return this._pageDefines.MainParams;
	}

	getFieldDefine(fieldName) {
		for (let i = 0; i < this._pageDefines.fields.length; i++) {
			if (fieldName === this._pageDefines.fields[i].FieldName) {
				return this._pageDefines.fields[i];
			}
		}
		return null;
	}

	getViewFields() {
		const fields = [];
		let index = 0;
		console.log('getViewFieldsgetViewFields', this._pageDefines);
		for (let i = 0; i < this._pageDefines.viewFields.length; i++) {
			console.log('[Debug][TabPageItem]fields', this._pageDefines.fields[index]);
			index = this._pageDefines.viewFields[i];
			fields.push(this._pageDefines.fields[index]);
		}
		console.log('[Debug][TabPageItem]getViewFields', fields);
		return fields;
	}

	getAddFields() {
		console.log('[Debug][TabPageItem] getAddFields, _pageDefines', this._pageDefines);
		const fields = [];
		let index = 0;
		for (let i = 0; i < this._pageDefines.addFields.length; i++) {
			index = this._pageDefines.addFields[i];
			const item = this._pageDefines.fields[index];
			if (item.AddProcessType === '0') {
				// 处理
				item.disabled = false;
				item.ReadOnly = false;
			} else if (item.AddProcessType == '2') {
				// 隐藏
				item.isAddHide = true;
			} else if (item.AddProcessType === '3') {
				// 只读
				item.ReadOnly = true;
				item.disabled = true;
			} else if (item.AddProcessType === '4') {
				// 必填
				item.ReadOnly = false;
				item.disabled = false;
			}
			// 表单宽度
			item.FormWidth = item.AddColWidth;
			fields.push(this._pageDefines.fields[index]);
		}
		console.log('getAddFields', fields);
		fields.sort(this.compare('AddSeqID'));
		return fields;
	}

	getUpdateFields() {
		const fields = [];
		let index = 0;
		console.log('1111111111111111111111111', this._pageDefines);
		for (let i = 0; i < this._pageDefines.updateFields.length; i++) {
			index = this._pageDefines.updateFields[i].index;
			console.log('2222222222222222222', this._pageDefines.updateFields[i], this._pageDefines.fields[index]);
			const item = this._pageDefines.updateFields[i];
			if (item.EditProcessType === '0') {
				this._pageDefines.fields[index].disabled = false;
			} else if (item.EditProcessType === '2') {
				this._pageDefines.fields[index].isEditHide = true;
			} else if (item.EditProcessType === '3') {
				this._pageDefines.fields[index].disabled = true;
				this._pageDefines.fields[index].ReadOnly = true;
			}
			// 表单宽度
			item.FormWidth = item.EditColWidth;
			// if (this._pageDefines.updateFields[i].IsReadOnlyNeed === '1') {
			// 	this._pageDefines.fields[index].disabled = true
			// 	this._pageDefines.fields[index].ReadOnly = true
			// }
			fields.push(this._pageDefines.fields[index]);
		}
		console.log('getUpdateFields', fields);
		fields.sort(this.compare('EditSeqID'));
		return fields;
	}

	getFilterFields() {
		const fields = [];
		let index = 0;
		for (let i = 0; i < this._pageDefines.filterFields.length; i++) {
			index = this._pageDefines.filterFields[i];
			fields.push(this._pageDefines.fields[index]);
		}
		return fields;
	}

	getSearchEvent() {
		return this._pageDefines.searchEvent;
	}

	getAddEvent() {
		return this._pageDefines.addEvent;
	}

	getExportEvent() {
		return this._pageDefines.exportEvent;
	}

	getImportEvent() {
		return this._pageDefines.importEvent;
	}

	getPagePrintEvent() {
		return this._pageDefines.pageprintEvent;
	}

	getTemPrintEvent() {
		return this._pageDefines.temprintEvent;
	}

	getOtherEvents() {
		return this._pageDefines.otherEvents;
	}

	getOptCols() {
		console.log('vvvvvvvvvvvvvvvvvv', this._pageDefines.optCols);
		return this._pageDefines.optCols;
	}

	// 返回加载到
	async loadPage(id) {
		const pageDefines = this._pageDefines;
		console.log('[Debug][TabPageItem]loadPage', pageDefines);
		// 从数据库中加载
		// const pageData = await queryPageDefine({ PageID: id })
		const pageData = await httpRequest.SyncPost('/eslithe/queryDefineNew.action', { PageID: id, SubSysID: BASE_API.SubSysID }, {}, headers);

		if (!pageData || !pageData.Records || pageData.Records.length === 0) {
			console.log('Failed to load table page define, page id: ', id);
			return null;
		}
		const pageRes = pageData.Records[0];
		pageDefines.TabName = pageRes.TabName;
		console.log('pageRes', pageRes);
		if (pageRes === undefined || pageRes === null || pageRes === '') {
			console.log('Failed to load table page define, page id: ', id);
			return null;
		}
		if (pageRes.MainParams && pageRes.MainParams !== '') {
			pageDefines.MainParams = formatStr2Obj(pageRes.MainParams);
		}

		pageRes.MainParams = null;
		if (pageRes.SearchButtun && pageRes.SearchButtun !== '') {
			pageDefines.searchEvent = formatStr2Obj(pageRes.SearchButtun);
		}
		pageRes.SearchButtun = null;

		if (pageRes.AddButtun && pageRes.AddButtun !== '') {
			pageDefines.addEvent = formatStr2Obj(pageRes.AddButtun);
		}
		pageRes.AddButtun = null;

		if (pageRes.ExportButtun && pageRes.ExportButtun !== '') {
			pageDefines.exportEvent = formatStr2Obj(pageRes.ExportButtun);
		}
		pageRes.ExportButtun = null;

		if (pageRes.ImportButton && pageRes.ImportButton !== '') {
			pageDefines.importEvent = formatStr2Obj(pageRes.ImportButton);
		}
		pageRes.ImportButton = null;

		if (pageRes.PagePrintButton && pageRes.PagePrintButton !== '') {
			pageDefines.pageprintEvent = formatStr2Obj(pageRes.PagePrintButton);
		}
		pageRes.PagePrintButton = null;

		if (pageRes.TemPrintButton && pageRes.TemPrintButton !== '') {
			pageDefines.temprintEvent = formatStr2Obj(pageRes.TemPrintButton);
		}
		pageRes.TemPrintButton = null;

		if (pageRes.ButtunDefine && pageRes.ButtunDefine !== '') {
			pageDefines.otherEvents = formatStr2Obj(pageRes.ButtunDefine);
		}

		if (pageRes.ImportTemp && pageRes.ImportTemp !== '') {
			pageDefines.ImportTemp = pageRes.ImportTemp;
		}
		if (pageRes.TableConfig && pageRes.ButtunDefine !== '') {
			pageRes.TableConfig = formatStr2Obj(pageRes.TableConfig);
		}
		pageRes.ButtunDefine = null;

		pageDefines.pageDefine = pageRes;
		console.log('Table page define: ', pageRes);
		console.log('Table page define MainParams: ', pageDefines.MainParams);
		let res = await this.loadPageFields(id, pageDefines);
		if (!res) {
			return null;
		}
		res = await this.loadColOpts(id, pageDefines);
		if (!res) {
			return null;
		}
		console.log('Table page define: ', pageDefines);
		return pageDefines;
	}

	async loadPageFields(id, pageDefines) {
		// const res = await queryColField({ PageID: id, limit: 100, current: 1 })
		// console.log('tab_page_item loadPageFields queryColField', res)
		const res = await httpRequest.SyncPost('/eslithe/queryFieldDefineNew.action', null, { PageID: id, limit: 100, current: 1 }, headers);
		// console.log('tab_page_item loadPageFields SyncPost', res)

		const fieldRes = res.Records;
		console.log('=======================================', fieldRes);
		if (fieldRes === undefined || fieldRes === null || fieldRes === '') {
			console.error('[Error][TabItem][LoadPage]Failed to load table page fields, page id: ', id);
			return false;
		}
		let inputDef = null;
		let depend = null;
		let options = null;
		for (let i = 0; i < fieldRes.length; i++) {
			// debugger
			inputDef = null;
			if (fieldRes[i].InputDefine && fieldRes[i].InputDefine !== '') {
				inputDef = formatStr2Obj(fieldRes[i].InputDefine);
			}

			if (!this.checkField(fieldRes[i], inputDef)) {
				console.log('[Error][TabItem][LoadPage]Failed to load table page fields, page id: ', id);
				return false;
			}

			depend = [];
			if (inputDef !== null && inputDef.depend && inputDef.depend !== '') {
				depend = inputDef.depend.split(',');
			}

			let ColWidth = [0, 0];
			if (fieldRes[i].ColWidth && fieldRes[i].ColWidth !== '') {
				ColWidth = fieldRes[i].ColWidth.split(',');
				for (let j = 0; j < ColWidth.length; j++) {
					ColWidth[j] = Number(ColWidth[j]); // 0: 是表格中显示宽度，1是过滤条件中宽度
				}
				if (ColWidth.length !== 2) {
					ColWidth = [0, 0];
				}
			}
			const type = this.getType(fieldRes[i].InputType);
			if (type === 'img') {
				if (!inputDef) {
					inputDef = { listType: 'picture-card', limit: 1, drag: true, type: 'img' };
				} else {
					if (!inputDef.limit) {
						inputDef.limit = 1;
					}
					if (!inputDef.listType) {
						inputDef.listType = 'picture-card';
					}
					if (inputDef.type === undefined) {
						inputDef.type = '0';
					}
					if (inputDef.drag === undefined) {
						inputDef.drag = true;
					}
				}
			}

			options = null;
			if (inputDef && inputDef.options) {
				options = inputDef.options;
			} else {
				if (type === 'select') {
					options = EnumOptions.instance().getOptions(fieldRes[i].FieldName);
				}
			}
			console.log('wwwwwwwwwwwwww', fieldRes[i]);
			const field = {
				FieldName: fieldRes[i].FieldName, // 字段名
				InputType: fieldRes[i].InputType, // 输入组件类型,对应基础组件名
				tipstext: fieldRes[i].tipstext || '', // 输入时提示的文本内容
				inputDefine: inputDef, // 复杂对像时应的扩展配置：如图文等
				ColWidth: ColWidth, // 是一个数级，[0]表格中显示宽度，[1]过虑中显示宽度，0不限宽
				type: type, // 输入组件类型
				value: fieldRes[i].FieldName,
				prop: fieldRes[i].FieldName,
				label: fieldRes[i].DefViewTitle, //显示的标签名称
				options: options,
				doptions: [],
				depend: depend,
				AddProcessType: fieldRes[i].AddProcessType, // 添加表单处理类型：0:处理 1:不处理 2:隐藏 3:只读 4:必填
				AddColWidth: fieldRes[i].AddColWidth, // 添加的时候显示的宽度，0不限宽
				EditColWidth: fieldRes[i].EditColWidth, // 修改的时候显示的宽度，0不限宽
				EditProcessType: fieldRes[i].EditProcessType, // 修改表单处理类型：0:处理 1:不处理 2:隐藏 3:只读 4:必填
				isParentInData: fieldRes[i].isParentInData, // 是否上级传入：0:前端输入，1:参数传入 2:使用固定值 3:本地存储 4：表达式 对应表：isParentInData
				inputFieldName: fieldRes[i].inputFieldName, // 当InputDataType为1是：为传入参㶼名或Vuex里取值方法  对应表中inputFieldName
				EditSeqID: fieldRes[i].EditSeqID, // 修改的时候显示的顺序
				AddSeqID: fieldRes[i].AddSeqID, // 添加的时候显示的顺序
				IfCascadeShow: fieldRes[i].IfCascadeShow, // 是否开否级联
				// 级联配置 json,type:"value"/"change"; label:(级联父级字段名); value:(触发事件的目标值" 当type为value时该字段有效)
				// type:"value"/"change"  value:当关联字段达一定值进触发操作，change：当关联字段发生变更时触发操作
				CascadeCfg: fieldRes[i].CascadeCfg ? JSON.parse(fieldRes[i].CascadeCfg.replace(/\\/g, '')) : '',
				// 小数精度 json, {open: '0|1', digit: 2}   open:是否需要转换，digit：取小数的位数
				accuracy: fieldRes[i].accuracy ? JSON.parse(fieldRes[i].accuracy.replace(/\\/g, '')) : '',
				// 数据存储的位置， 'file/database'
				dataStorageMode: fieldRes[i].dataStorageMode,
				DefaultValue: fieldRes[i].DefaultValue,

				InputCheck: fieldRes[i].InputCheck ? JSON.parse(fieldRes[i].InputCheck.replace(/\\\\/g, '')) : '',
				ViewSeqID: fieldRes[i].ViewSeqID,
				Extend: fieldRes[i].Extend,
			};
			if (field.InputType === '12') {
				field.Language = field.tipstext;
				field.tipstext = '';
			}
			if (field.Extend) {
				field.Extend = JSON.parse(field.Extend.replace(/\\/g, ''));
			} else {
				field.Extend = {};
			}
			if (field.InputCheck.value) {
				// 此处将校验里面的#号换成\
				field.InputCheck.value = field.InputCheck.value.replaceAll('#', '\\');
			}
			console.log('field', field);
			pageDefines.fields.push(field);

			if (fieldRes[i].IsViewInTab === '1') {
				pageDefines.viewFields.push(i);
				field.IsViewInTab = true;
			}
			if (['0'].includes(fieldRes[i].AddProcessType)) {
				if (fieldRes[i].IsAddNeed === '0') {
					fieldRes[i].AddProcessType = '1';
				} else if (fieldRes[i].IsReadOnlyNeed === '1') {
					fieldRes[i].AddProcessType = '3';
				}
			}
			if (['0', '2', '3', '4'].includes(fieldRes[i].AddProcessType) || type === 'exp') {
				console.log('[Debug][TabPageItem]loadPageFields, fieldRes,IsAddNeed', fieldRes[i], i, type);
				pageDefines.addFields.push(i);
			}

			if (['0'].includes(fieldRes[i].EditProcessType)) {
				if (fieldRes[i].IsReadOnlyNeed === '1') {
					fieldRes[i].EditProcessType = '3';
				} else if (fieldRes[i].IsUpdateNeed === '0') {
					fieldRes[i].EditProcessType = '1';
				}
			}
			if (['0', '2', '3', '4'].includes(fieldRes[i].EditProcessType) || type === 'exp') {
				console.log('[Debug][TabPageItem]loadPageFields, fieldRes,IsUpdateNeed', fieldRes[i], i, type);
				pageDefines.updateFields.push({ ...fieldRes[i], index: i });
			}
			// 过滤字段需要排序
			if (fieldRes[i].IsFilter === '1') {
				field.IsFilter = true;
				let fieldIndex = 0;
				let j = 0;
				for (j = 0; j < pageDefines.filterFields.length; j++) {
					fieldIndex = pageDefines.filterFields[j];
					if (fieldRes[i].FilterSeqID < fieldRes[fieldIndex].FilterSeqID) {
						pageDefines.filterFields.splice(j, 0, i);
						break;
					}
				}
				if (j === pageDefines.filterFields.length) {
					pageDefines.filterFields.push(i);
				}
			}
		}

		return true;
	}

	async loadColOpts(id, pageDefines) {
		// const res = await queryColOpt({ PageID: id })
		const res = await httpRequest.SyncPost('/eslithe/queryBtnDefineNew.action', { PageID: id }, {}, headers);
		// 列操作
		const colOptRes = res.Records || [];
		if (!colOptRes || colOptRes.length === 0) {
			return true;
		}
		console.log('Load table page colOpts: ', colOptRes);
		// optCols: [], // {ColumnName: 'xx', Opts: [{updateEvent: null,deleteEvent: null, otherEvents: []}]}
		// pageDefines.optCols
		for (let i = 0; i < colOptRes.length; i++) {
			const newFixedCol = colOptRes[i].FixedCol.replace(/\\/g, '');
			const optColDefine = {
				ColumnName: colOptRes[i].ColumnName,
				buttonDefines: [],
				ColWidth: colOptRes[i].ColWidth,
				ViewSeqID: colOptRes[i].ViewSeqID,
				FixedCol: JSON.parse(newFixedCol),
			};
			this.parseColButton(colOptRes[i].Buttom1, optColDefine);
			this.parseColButton(colOptRes[i].Buttom2, optColDefine);
			this.parseColButton(colOptRes[i].Buttom3, optColDefine);
			this.parseColButton(colOptRes[i].Buttom4, optColDefine);
			this.parseColButton(colOptRes[i].Buttom5, optColDefine);
			this.parseColButton(colOptRes[i].Buttom6, optColDefine);
			pageDefines.optCols.push(optColDefine);
		}

		return true;
	}

	parseColButton(buttonData, optColDefine) {
		if (buttonData && buttonData !== '') {
			const colOpt = formatStr2Obj(buttonData);
			if (!colOpt) {
				return;
			}
			if (colOpt.type === ColOptType_Update) {
				if (!colOpt.event || !colOpt.event.url) {
					console.log('[Error]The update col button define, no define the event or url, define: ', colOpt);
					return;
				}
				this._pageDefines.updateEvent = colOpt;
			} else if (colOpt.type === ColOptType_Delete) {
				if (!colOpt.event || !colOpt.event.url) {
					console.log('[Error]The update col button define, no define the event or url, define: ', colOpt);
					return;
				}
				this._pageDefines.deleteEvent = colOpt;
			}
			optColDefine.buttonDefines.push(colOpt);
		}
	}

	checkField(fieldDefine, inputDefine) {
		if (fieldDefine.InputType === '4') {
			if (!inputDefine || !inputDefine.inputdisplay || !inputDefine.inputflag || !inputDefine.event || !inputDefine.event.url) {
				console.error('[Error]The select list field define invalid, define: ', fieldDefine);
				return false;
			}
		}
		return true;
	}

	getType(n) {
		switch (n) {
			case '0':
				return 'input';
			case '1':
				return 'select';
			case '2':
				return 'date';
			case '3':
				return 'time';
			case '4':
				return 'select_d';
			case '5':
				return 'textarea';
			case '6':
				return 'systime';
			case '7':
				return 'img';
			case '8':
				return 'rich';
			case '9':
				return 'vedio';
			case '10':
				return 'cascader';
			case '11':
				return 'exp';
			case '12':
				return 'code-editor';
			default:
				return 'input';
		}
	}

	// 数组对象排序
	compare(property) {
		return function (obj1, obj2) {
			let value1 = obj1[property];
			let value2 = obj2[property];
			return value1 - value2; // 升序
		};
	}
}

export default TabPageItem;
